<template>
  <div class="content">
    <StudentMenu/>
    <main class="ml-64 flex-1 p-6 bg-gray-50 min-h-screen">
      <header class="flex justify-between items-center mb-6">
        <div class="flex items-center space-x-2">
          <svg class="w-7 h-7 text-blue-500" fill="currentColor" viewBox="0 0 24 24">
            <path
                d="M12 12c2.7 0 5-2.3 5-5s-2.3-5-5-5-5 2.3-5 5 2.3 5 5 5zm0 2c-3.3 0-10 1.7-10 5v3h20v-3c0-3.3-6.7-5-10-5z"/>
          </svg>
          <h1 class="text-2xl font-semibold text-gray-800">智能模拟面试</h1>
        </div>
      </header>
      <el-tabs v-model="activeTab" type="card">
        <!-- 编辑标签页 -->
        <el-tab-pane label="面试" name="edit">
          <div class="row">
            <div class="col-md-12">
              <el-card shadow="never">
                <div id="chat-container">
                  <div id="response-container">
                    <label for="response"><strong>HR面试官：{{HrRoleForm.NAME}} {{HrRoleForm.SEX}}, 是一个{{HrRoleForm.CHARACTER}}的HR，面试岗位:{{HrRoleForm.JOB_NAME}}，面试的场地是{{HrRoleForm.LOCATION}}。</strong></label>
                    <!--                    <textarea id="response" v-model="answer" placeholder="智能回复会显示在这里…" readonly rows="20"></textarea>-->
                    <div class="fake-textarea" v-html="formattedAnswer"></div>
                    <button @click="copyAnswer" id="copyBtn" type="button">复制回复</button>
                  </div>

                  <form id="chat-form" onsubmit="return false;">
                    <label for="question"><strong>输入回答：</strong></label>
                    <textarea id="question" v-model="question" name="question" placeholder="在此输入您的问题…"
                              rows="4"></textarea>

                    <div style="display: flex; align-items: center; gap: 60px;">
                      <label>
                        <input v-model="isChecked" type="checkbox"/>
                        提交个人信息
                      </label>

                      <button id="askBtn" type="button" @click="clearChatHistory">清除记录</button>
                      <button id="askBtn" type="button" @click="askQuestion"> 提交回答</button>
                      <button id="askBtn" type="button" @click="dialogVisible = true"> 定义HR角色</button>
                      <button id="askBtn" type="button" @click="copyPersonalInfo"> 复制个人信息</button>
                    </div>

                  </form>
                </div>

                <!-- 定义角色：姓名、性别、性格、面试岗位名称、面试场地 -->
                <el-dialog
                    title="定义HR面试官角色"
                    :visible.sync="dialogVisible"
                    width="30%"
                >
                  <el-form :model="HrRoleForm" :rules="rules" label-width="100px">

                    <!-- 角色名称 -->
                    <el-form-item label="角色名称" prop="NAME">
                      <el-input v-model="HrRoleForm.NAME"></el-input>
                    </el-form-item>

                    <!-- 性别 -->
                    <el-form-item label="性别" prop="SEX">
                      <el-select v-model="HrRoleForm.SEX" placeholder="请选择性别">
                        <el-option label="男" value="男"></el-option>
                        <el-option label="女" value="女"></el-option>
                      </el-select>
                    </el-form-item>

                    <!-- 性格 -->
                    <el-form-item label="性格" prop="CHARACTER">
                      <el-input v-model="HrRoleForm.CHARACTER" placeholder="例如：温和、严厉、风趣等"></el-input>
                    </el-form-item>

                    <!-- 面试岗位 -->
                    <el-form-item label="面试岗位" prop="JOB_NAME">
                      <el-input v-model="HrRoleForm.JOB_NAME"></el-input>
                    </el-form-item>

                    <!-- 面试场地 -->
                    <el-form-item label="面试场地" prop="LOCATION">
                      <el-input v-model="HrRoleForm.LOCATION"></el-input>
                    </el-form-item>
                  </el-form>

                  <!-- 底部按钮 -->
                  <span slot="footer" class="dialog-footer">
                  <el-button @click="dialogVisible = false">保存</el-button>
                </span>
                </el-dialog>
              </el-card>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

    </main>
  </div>
</template>

<script>
import StudentMenu from "@/components/student/Student_menu.vue";

import E from 'wangeditor';
import dayjs from 'dayjs';
import axios from 'axios';
import {EventBus} from "@/event-bus";
import {ServerIP} from "@/SystemConfig"
import SockJS from "sockjs-client";
import {NOWIP} from "@/NOWIP";
import Stomp from "webstomp-client";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import {upperFirst} from "lodash/string";

export default {
  name: 'StudentMnmsView',
  components: {StudentMenu},
  filters: {
    dateFormat(val) {
      return val ? dayjs(val).format('YYYY-MM-DD HH:mm') : '--';
    }
  },
  data() {
    return {
      dialogVisible: false,
      HrRoleForm: {
        NAME: '罗邓',
        SEX: '男',
        CHARACTER: '严厉',
        JOB_NAME: 'java开发工程师',
        LOCATION: '教学楼101',
      },
      rules: {
        NAME: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        SEX: [{ required: true, message: '请选择性别', trigger: 'change' }],
        CHARACTER: [{ required: true, message: '请输入性格', trigger: 'blur' }],
        JOB_NAME: [{ required: true, message: '请输入岗位名称', trigger: 'blur' }],
        LOCATION: [{ required: true, message: '请输入面试场地', trigger: 'blur' }]
      },


      isEditorUpdating: false, // 新增：防止循环更新标志
      isChecked: false,
      UserInfo: {
        id: '',
        name: '',
        role: '',
        username: '',
      },
      // 用来保存 STOMP 客户端实例
      stompClient: null,
      question: "",
      answer: "",
      activeTab: 'edit',
      form: {
        JLDM: '',
        HTML: '',
        TEXT: '',
      },
      student: {},
      currentRow: null,
      editor: null,
      previewVisible: false,
      previewContent: ''
    };
  },
  mounted() {
    this.getLoginUserInfo();// 获取登录用户信息
    this.connectWebSocket();
    this.$socket.subscribe(this.handleWebSocketMessage)
  },
  beforeDestroy() {
    if (this.editor) {
      this.editor.destroy();
      this.editor = null;
    }
    this.$socket.unsubscribe(this.handleWebSocketMessage)
  },
  methods: {
    loadStudents() {
      axios.get(`/student/getStudentDataNewInterface?YHM=${this.UserInfo.username}&YHSFDM=4&QYDM=2`).then(response => {
        this.student = response.data.data[0];
      })
          .catch(error => {
            console.error('加载学生数据失败', error);
            this.$message.error('加载学生数据失败:' + error.message);
          });
    },
    copyPersonalInfo() {
      const safe = (val) => val !== undefined && val !== null ? val : "未定义";

      const text = `注：姓名 ${safe(this.student.XSXM)}，性别 ${safe(this.student.XSXB)}，出生日期 ${safe(this.student.BIRTH)}，年龄 ${safe(this.student.NL)} 岁，` +
          `学号 ${safe(this.student.YHM)}，民族 ${safe(this.student.MZ)}，政治面貌 ${safe(this.student.ZZMM)}，入学年份 ${safe(this.student.RXNF)}，毕业年份 ${safe(this.student.BYNF)}，` +
          `所在学校 ${safe(this.student.SZXX)}，学历 ${safe(this.student.XLMC)}，学位 ${safe(this.student.XW)}，专业 ${safe(this.student.ZYMC)}，` +
          `班级 ${safe(this.student.BJMC)}，年级 ${safe(this.student.SSNJ)}，学制 ${safe(this.student.XZ)}，` +
          `当前状态 ${safe(this.student.JYZT)}，身份证号 ${safe(this.student.SFZH)}，联系电话 ${safe(this.student.LXDH)}，邮箱 ${safe(this.student.YXDZ)}，` +
          `所在地 ${safe(this.student.SFCS)}，个人照片路径：${safe(this.student.XSZP)}。`;

      // 创建隐藏 textarea 元素
      const textarea = document.createElement('textarea');
      textarea.value = text;
      textarea.setAttribute('readonly', '');
      textarea.style.position = 'absolute';
      textarea.style.left = '-9999px';
      document.body.appendChild(textarea);

      // 选中内容并执行复制命令
      textarea.select();
      try {
        const success = document.execCommand('copy');
        if (success) {
          this.$message.success("复制成功");
        } else {
          this.$message.error("复制失败");
        }
      } catch (err) {
        this.$message.error("复制异常");
        console.error("复制出错:", err);
      }

      // 移除 textarea
      document.body.removeChild(textarea);
    },
    clearChatHistory() {
      let clearForm = new FormData();
      clearForm.append("twz", this.UserInfo.username);
      clearForm.append("twzsfdm", 4);

      axios.post("/aidhjlk/clear", clearForm).then(response => {
        if (response.data.result) {
          this.$message.success("清除记录成功");
        } else {
          this.$message.error("清除记录失败:" + response.data.msg);
        }
      }).catch(error => {
        this.$message.error("清除记录失败:" + error.message);
      });

    },
    // 连接WebSocket
    connectWebSocket() {
      const socket = new SockJS(`http://${NOWIP}:83/chat`);
      this.stompClient = Stomp.over(socket);

      this.stompClient.connect({}, () => {
        this.stompClient.subscribe('/topic/messages', message => {
          const msg = JSON.parse(message.body);
          /*  answer:"一万字，是一个相对来说较为庞大的篇幅。在写作过程中，需要有足"
            question:
                "10000字！！"
            sendtime
                :
                "2025-05-07T05:02:25.530+00:00"
            twzsfdm
                :
                "4"
            twzyhm
                :
                "20213260021"
            twzyzxm
                :
                "陈洁梅"*/
          //一点点把回答放到answer中
          this.answer = msg.answer;
        });
      });
    },
    handleWebSocketMessage(msg) {
      console.log('Received message in component:', msg)
      // 处理你的消息
    },
    askQuestion() {
      console.log(this.question);
      // 提问者: this.UserInfo.username
      // 提问者姓名: this.UserInfo.name
      // 问题: this.question
      if (this.question.length === 0) {
        this.$message.warning("请输入问题！");
        return;
      }
      let newQuestion = `记住你是一名HR：${this.HrRoleForm.NAME},${this.HrRoleForm.SEX}, 是一个${this.HrRoleForm.CHARACTER}的HR，面试岗位:${this.HrRoleForm.JOB_NAME}，面试的场地是${this.HrRoleForm.LOCATION}，下面是学生的回答:${this.question}`;
      console.log(this.isChecked)
      if (this.isChecked) {

        /* {
            {
             "ID": 1224,
             "XSXM": "陈洁梅",
             "XSXB": "女",
             "BIRTH": "2001-10-02",
             "NL": 24,
             "YHM": "20213260021",
             "ZYMC": "信息管理与信息系统",
             "SFZH": "450981200110065049",
             "ZZMM": "共青团员",
             "SSNJ": "2021",
             "XZ": "四年制",
             "MZ": "汉族",
             "XSXH": "20213260021",
             "BJMC": "2021级信息管理与信息系统",
             "SSBJ": 1292,
             "XLMC": "本科",
             "JYZT": "实习中",
             "XSZP": "/img/upload/Userpofile/20213260021_1742207649940_.jpg",
             "FZJS": 0,
             "JSMC": null,
             "STUID": 1224,
             "YXDZ": "abcd@qq.com",
             "SFCS": "广西南宁",
             "LXDH": "19195872108",
             "XSZY": ".NET研发工程师",
             "SZXX": "广西中医药大学",
             "RXNF": 2002,
             "BYNF": 2027,
             "XW": "学士学位"
         }
         }*/
        newQuestion = newQuestion + ` 注：姓名 ${this.student.XSXM}，性别 ${this.student.XSXB}，出生日期 ${this.student.BIRTH}，年龄 ${this.student.NL} 岁，` +
            `学号 ${this.student.YHM}，民族 ${this.student.MZ}，政治面貌 ${this.student.ZZMM}，入学年份 ${this.student.RXNF}，毕业年份 ${this.student.BYNF}，` +
            `所在学校 ${this.student.SZXX}，学历 ${this.student.XLMC}，学位 ${this.student.XW}，专业 ${this.student.ZYMC}，` +
            `班级 ${this.student.BJMC}，年级 ${this.student.SSNJ}，学制 ${this.student.XZ}，` +
            `当前状态 ${this.student.JYZT}，身份证号 ${this.student.SFZH}，联系电话 ${this.student.LXDH}，邮箱 ${this.student.YXDZ}，` +
            `所在地 ${this.student.SFCS}`;

      }

      // 发送给后台处理
      const newMsg = {
        twzyhm: this.UserInfo.username,//提问者用户名
        twzsfdm: 4,// 提问者身份代码
        twzyzxm: this.UserInfo.name,// 提问者姓名
        question: newQuestion,// 消息内容
        sendtime: new Date().getTime()
      };


      try {
        this.stompClient.send("/app/chat2", JSON.stringify(newMsg));
      } catch (error) {
        this.handleError('消息发送失败', error);
      }
    },
    // 获取学生信息
    getStudentDataByUsername(yhm) {
      axios.get(`/student/getStudentByUsernameOrId?usernameOrId=${yhm}&type=username`).then(response => {
        if (response.data.result) {
          this.UserInfo.id = response.data.data.id;
        } else {
          this.$message.error("获取学生信息失败:" + response.data.msg);
        }
      }).catch(error => {
        console.log(error);
        this.$message.error("获取学生信息失败，网络错误！");
      });
    },
    async getLoginUserInfo() {
      try {
        this.loading = true;
        const response = await axios.get('/user/checkSession');
        if (!response.data.result) {
          this.handleAuthFailure(response.data.msg);
        } else {
          this.UserInfo = {
            name: response.data.name,
            role: response.data.role,
            username: response.data.username
          };
          this.loadStudents();
          this.getStudentDataByUsername(this.UserInfo.username);
        }
      } catch (error) {
        console.error('获取用户信息失败，网络错误！', error);
        this.handleAuthFailure();
      }
    },

    handleAuthFailure() {
      EventBus.$emit('show-auth-popup');
      setTimeout(() => {
        this.$router.push({name: 'StudentLoginView'});
      }, 1000);
    },
    copyAnswer(){
      const safe = (val) => val !== undefined && val !== null ? val : "未定义";

      const text=this.answer;
      // 创建隐藏 textarea 元素
      const textarea = document.createElement('textarea');
      textarea.value = text;
      textarea.setAttribute('readonly', '');
      textarea.style.position = 'absolute';
      textarea.style.left = '-9999px';
      document.body.appendChild(textarea);

      // 选中内容并执行复制命令
      textarea.select();
      try {
        const success = document.execCommand('copy');
        if (success) {
          this.$message.success("复制成功");
        } else {
          this.$message.error("复制失败");
        }
      } catch (err) {
        this.$message.error("复制异常");
        console.error("复制出错:", err);
      }

      // 移除 textarea
      document.body.removeChild(textarea);
    }
  },
  computed: {
    studentId() {
      return this.$store.state.user.id;
    },
    formattedAnswer() {
      // 替换所有 `\n` 成 <br>（注意这里是匹配字符串中的字面量 \n）
      return this.answer.replace(/\\n/g, '<br>');
    }
  }
};
</script>
<style scoped>
#chat-container {
  /*max-width: 600px;*/
  margin: 2px auto;
  padding: 15px;
  /* border: 1px solid #ccc;
   border-radius: 8px;*/
  font-family: sans-serif;
}

textarea {
  width: 100%;
  box-sizing: border-box;
  padding: 8px;
  margin: 5px 0 10px;
  border: 1px solid #aaa;
  border-radius: 4px;
  resize: vertical;
  font-size: 14px;
}


.editor-container {
  /*border: 1px solid #dcdfe6;*/
  border-radius: 4px;
  padding: 10px;
  /* 设置编辑器高度 */
  min-height: 300px;
}

.w-e-toolbar {
  /* border-bottom: 1px solid #dcdfe6 !important;*/
}

.w-e-text-container {
  height: 300px !important;
}

.form-container {
  padding: 2px;
  background: #ffffff;
  border-radius: 0px;
  /*  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);*/
}

.luodeng button {
  margin-right: 30px !important;
}

.fake-textarea {
  border: 1px solid #ccc;
  padding: 8px;
  font-family: inherit;
  font-size: 14px;
  line-height: 1.5; /* 每行高度约 21px */
  height: calc(1.5em * 20); /* 20 行 */
  overflow-y: auto;
  background-color: #f9f9f9;
  white-space: normal; /* 必须是 normal，否则 <br> 无效 */
  word-break: break-word;
}
</style>
